<?php
/* explain:		common class
 * Project:     marsems
 * File:        Common.php
 *
 * @ link 		http://www.marems.com/lib/
 * @ Email		ldmmyx@hotmail.com
 * @ copyright 	2007  ivan.ling
 * @ author 	 ivan.ling
 * @ version 	1.0
 *
 * @ --- function list ---
 * @ mutilPager($total, $page, $disDataCount, $url)	--> split page function
 */

include_once("Popedom.php");
class Common extends Popedom
{
	public $total;			//-- data total
	public $pagenav;		//-- navication bar
	public $goNav;			//-- navication bar
	
	public $page;			//-- current page
	public $prePage;			//-- previous page
	public $nextPage;			//-- next page
	
	public $disDataCount;	//-- display data total
	public $disPageCount;	//-- display page total
	public $firstcount;		//-- first page position
	public $pagecount;		//-- page total, lastest page
	
	public $currentStartPostion;
	public $currentEndPostion;
	
	function Common()
	{
		parent::Popedom();
		
		$this->total = 0;
		$this->pagenav = '';
		$this->page = 1;
		$this->disDataCount = 20;
		$this->disPageCount = 10;
		$this->firstcount = 1;
		
	}
	
	public function getPage()
	{
		return $this->page;	
	}
	
	public function getPrePage()
	{
		$this->prePage = $this->page - 1;
		
		if($this->prePage > 1)
			return $this->prePage;
		else
			return 1;	
	}
	
	public function getNextPage()
	{
		$this->nextPage = $this->page + 1;
		
		if($this->nextPage > 1)
			return $this->nextPage;
		else
			return 1;	
	}
	
	public function getPageList($pagecount = 5)
	{
		$arrReturn = array();
		
		if($pagecount > $this->pagecount)
			$pagecount = $this->pagecount;
			
		$firstPage = floor($this->page / 2);
		
		if(($this->pagecount - $this->page) < ($this->page - $firstPage)){
			$firstPage = $this->pagecount - $pagecount;
		}
		
		if($firstPage <= 0)
			$firstPage = 1;
		
		$endPage = $firstPage + $pagecount;
		
		if($endPage > $this->pagecount)
			$pagecount = $this->pagecount;
			
		for($i = $firstPage; $i < $endPage; $i++){
			$arrReturn[] = $i;
		}
		
		return $arrReturn;
	}
	
	public function getStartPosition()
	{
		return $this->currentStartPostion;	
	}
	
	public function getEndPostion()
	{
		return $this->currentEndPostion;
	}
	
	public function getTotal()
	{
		return $this->total;
	}
	
	public function getPageCount()
	{
		return $this->pagecount;
	}
	
	/**
	 * split page paramter
	 *
	 * @param  string total      	data total
	 * @param  string page       	current page										
	 * @param  string disDataCount	current page	 
	 * @param  string url      	 	defaul page url											
	 * @param  return string     	return navication bar string										
	 */
	public function mutilPager($total, $page, $disDataCount, $url = '')
	{
		global $_SERVER, $_GET;

		$this->total = $total;
		
		if(empty($total)){
			$this->page  		= 0;
			$this->pagecount 	= 0;
			$this->firstcount 	= 0;
			
			$this->pagenav 	= '';
			$this->goNav 	= '';
			
			return 'There be not find data.';
		}
		
		if(empty($disDataCount)){
			return 'find '.$total.' data.';
		}
		
		if(!isset($page) || empty($page)){
			if(isset($_GET['page']))
				$page = $_GET['page'];
			else 
				$page = 1;
		}
		
		$this->page  = $page;
		
		if(empty($url))//--- if url is empty . url equal current page url
			$url = $_SERVER["REQUEST_URI"];

		/*--- URL process ---*/
		$parse_url = parse_url($url);
		if(isset($parse_url["query"]))
			$url_query = $parse_url["query"]; //--- get url query string 
		else
			$url_query = '';
		if($url_query){
			$url_query=ereg_replace("(^|&)page=$page","",$url_query);

			$url = str_replace($parse_url["query"],$url_query,$url);//---
			
			if($url_query)//---
				$url .= "&page";
			else 
				$url .= "page";
		}else
			$url .= "?page";
		
		/*--- page process ---*/
		$this->disDataCount = $disDataCount;
		
		$this->pagecount = ceil($total/$disDataCount); //--- lastest page
		$this->page = min($this->pagecount, $this->page);
		//$prepg = $page-1; 				
		//$nextpg =($page == $this->pagecount ? 0 : $page + 1); 
		$this->firstcount=($this->page - 1) * $this->disDataCount;

		$this->currentStartPostion = $this->firstcount + 1;
		$this->currentEndPostion = min($this->firstcount + $this->disDataCount, $total);
		
		/*--- start navication bar ---*/
        $this->pagenav = ' <B>'.($total?($this->firstcount + 1):0)."</B>-<B>".min($this->firstcount + $this->disDataCount, $total)."</B> of ". $total . "  ";
		
        $this->goNav ="<select name='topage' size='1' onchange='window.location=\"$url=\"+this.value'>\n";
		for($i = 1;$i <= $this->pagecount; $i++){
			if($i == $this->page)
				$this->goNav .= "<option value='$i' selected>$i</option>\n";
			else
				$this->goNav .= "<option value='$i'>$i</option>\n";
		}
		$this->goNav .= "</select> ";
		
		/*--- ---*/
		if($this->pagecount <= 1){
			return  $this->pagenav;
		}
		
		if($this->page <= $this->pagecount){
			$this->pagenav .= ' < ';
			$istart = (floor($this->page / $this->disPageCount)) * $this->disPageCount;
			
			if($this->page == $istart + 1 && $this->page != 1)
				$istart = (floor($this->page / $this->disPageCount) - 1) * $this->disPageCount;
				
			$iend = $istart + $this->disPageCount;
			
			
			if($iend > $this->pagecount)
				$iend = $this->pagecount;
							
			for($i = $istart; $i < $iend; $i++){
				if($this->page == ($i + 1))
					$this->pagenav .=  ($i + 1) . ' ';
				else
					$this->pagenav .=  "<a href='$url=" . ($i + 1) . "'>" . ($i + 1) . "</a> ";
			}
			$this->pagenav .= '> ';
		}
			
		/*-- go to some page --
		$this->pagenav.=" Go <select name='topage' size='1' onchange='window.location=\"$url=\"+this.value'>\n";
		for($i = 1;$i <= $this->pagecount; $i++){
			if($i == $page)
				$this->pagenav .= "<option value='$i' selected>$i</option>\n";
			else
				$this->pagenav .= "<option value='$i'>$i</option>\n";
		}
		$this->pagenav .= "</select> ";*/
//		$this->pagenav .= " Go " . $this->goNav;
		
		return $this->pagenav;
	}
	
	
	/**
	 * split page paramter
	 *
	 * @param  string total      	data total
	 * @param  string page       	current page										
	 * @param  string disDataCount	current page	 
	 * @param  string url      	 	defaul page url											
	 * @param  return string     	return navication bar string										
	 */
	public function mutilPagerRewriter($total, $page, $disDataCount, $url)
	{
		global $_SERVER, $_GET;

		$this->total = $total;
		
		if(empty($total)){
			$this->page  		= 0;
			$this->pagecount 	= 0;
			$this->firstcount 	= 0;
			
			$this->pagenav 	= '';
			$this->goNav 	= '';
			
			return 'There be not find data.';
		}
		
		if(empty($disDataCount)){
			return 'find '.$total.' data.';
		}
		
		if(!isset($page) || empty($page)){
			if(isset($_GET['page']))
				$page = $_GET['page'];
			else 
				$page = 1;
		}
		
		$this->page  = $page;
		
		if(empty($url))//--- if url is empty . url equal current page url
			$url = $_SERVER["REQUEST_URI"];

		/*--- URL process ---*/
		$parse_url = parse_url($url);
		
		$isBeforQuery = true;
		$beforQuery	= '';
		$afterQuery	= '';
		
		$arrQuery = explode("_", basename($parse_url["path"]));
		$paramTotal = count($arrQuery);
		
		for($i = 0; $i < $paramTotal; $i++){
			if($isBeforQuery)	{
				if(!empty($beforQuery))
					$beforQuery .= '_';
				
				if($i == $paramTotal - 1){//-->> file name
					$beforQuery .= 'pg_';
					$afterQuery .=  '_';
					$afterQuery .=  $arrQuery[$i];
				}else{
					$beforQuery .= $arrQuery[$i];
					
					if($arrQuery[$i] == 'pg'){//--> is page premeter
						$beforQuery .= '_';
						$isBeforQuery = false;
						
						$i++;
					}
				}
			}else{
				if(!empty($beforQuery) && empty($afterQuery))
					$afterQuery .= '_';
				
				$afterQuery .=  $arrQuery[$i];
			}
		}
			
		/*--- page process ---*/
		$this->disDataCount = $disDataCount;
		
		$this->pagecount = ceil($total/$disDataCount); //--- lastest page
		$this->page = min($this->pagecount, $this->page);
		//$prepg = $page-1; 				
		//$nextpg =($page == $this->pagecount ? 0 : $page + 1); 
		$this->firstcount=($this->page - 1) * $this->disDataCount;

		/*--- start navication bar ---*/
        $this->pagenav = ' <B>'.($total?($this->firstcount+1):0)."</B>-<B>".min($this->firstcount+$this->disDataCount,$total)."</B> of ". $total . "  ";
		
        $this->goNav ="<select name='topage' size='1' onchange='window.location=\"$beforQuery\"+this.value+\"$afterQuery\"'>\n";
		for($i = 1;$i <= $this->pagecount; $i++){
			if($i == $this->page)
				$this->goNav .= "<option value='$i' selected>$i</option>\n";
			else
				$this->goNav .= "<option value='$i'>$i</option>\n";
		}
		$this->goNav .= "</select> ";

		/*--- ---*/
		if($this->pagecount <= 1){
			return  $this->pagenav;
		}
		
		if($this->page <= $this->pagecount){
			$this->pagenav .= ' < ';
			$istart = (floor($this->page / $this->disPageCount)) * $this->disPageCount;
			
			if($this->page == $istart + 1 && $this->page != 1)
				$istart = (floor($this->page / $this->disPageCount) - 1) * $this->disPageCount;
				
			$iend = $istart + $this->disPageCount;
			
			
			if($iend > $this->pagecount)
				$iend = $this->pagecount;
							
			for($i = $istart; $i < $iend; $i++){
				$this->pagenav .=  "<a href='$beforQuery" . ($i + 1) . "$afterQuery'>" . ($i + 1) . "</a> ";
			}
			$this->pagenav .= '> ';
		}
			
		$this->pagenav .= " Go " . $this->goNav;
		
		return $this->pagenav;
	}
	
	public function arrMutilPage($arrData, $page, $pagesize)
	{
		$total = count($arrData);
		if(empty($page))
			$page = $this->page;
			
		if(empty($pagesize))
			$pagesize = $this->disDataCount;
			
		$pageTotal = ceil($total / $pagesize);
		if($page > $pageTotal)
			$page = $pageTotal;
		
		$startpos 	= ($page - 1) * $pagesize;
		$endpos 	= $startpos + $pagesize;
		
		$datalist = '';
		
		for($i = 0; $i < $total; $i++){
			if($i >= $startpos && $i < $endpos){
				
				if(!empty($datalist))
					$datalist .= ',';
				$datalist .= $arrData[$i];
			}
			
			if($i > $endpos)
				break;
		}
		
		$arrReturn = array();
		$arrReturn['page'] 		= $page;
		$arrReturn['pageTotal'] = $pageTotal;
		$arrReturn['datalist'] 	= $datalist;
		$arrReturn['pagesize'] 	= $pagesize;
		
		return $arrReturn;
	}
	
	public function getRow($DBtag, $sql)
	{
		$arrBack 	= array();
		$conn 		= null;
		
		try{
			$conn 	= $this->getConnection($DBtag);
			$rs  	= mysql_query($sql, $conn) or die("Invalid query: " . $sql . mysql_error($conn));

			if($rs && mysql_num_rows($rs) > 0){
				$arrBack = mysql_fetch_array($rs);
			}
			
			mysql_free_result($rs);
		}catch(Exception $e){
			echo mysql_error($conn) . $sql;
		}
		
		if($conn != null)
			$this->freeConnection($DBtag, $conn);
			
		return $arrBack;
	}
	
	public function isExisted($DBtag, $sql)
	{
		$isReturn 	= false;
		$conn 		= null;
		
		try{
			$conn 	= $this->getConnection($DBtag);
			$rs  	= mysql_query($sql, $conn) or die("Invalid query: " . $sql . mysql_error($conn));

			if($rs && mysql_num_rows($rs) > 0){
				$isReturn 	= true;
			}
		}catch(Exception $e){
			echo mysql_error($conn) . $sql;
		}
		
		if($conn != null)
			$this->freeConnection($DBtag, $conn);
			
		return $isReturn;
	}
	
	/* web list by condition
	 *
	 * @param  String DBtag # DB tag
	 * @param  String sql
	 * @return Array[][]
	 */
	public function getAllData($DBtag, $sql)
	{
		$arrBack 	= array();
		$conn 		= null;
		
		try{
			$conn 	= $this->getConnection($DBtag);
			$rs  	= mysql_query($sql, $conn);

			if($rs){
				while($arrCache = mysql_fetch_assoc($rs)){
					$arrBack[] = $arrCache;
				}
			}
		}catch(Exception $e){
			echo mysql_error($conn) . $sql;
		}
		
		if($conn != null)
			$this->freeConnection($DBtag, $conn);
			
		return $arrBack;
	}
	
	/* web list by condition
	 *
	 * @param  String DBtag # DB tag
	 * @param  String sql
	 * @return Array[][]
	 */
	public function update($DBtag, $sql)
	{
		$isreturn 	= false;
		$conn 		= null;
		
		try{
			$conn 	= $this->getConnection($DBtag);
			$rs  	= mysql_query($sql, $conn);

			if($rs){
				$isreturn = true;
			}
		}catch(Exception $e){
			echo mysql_error($conn) . $sql;
		}
		
		if($conn != null)
			$this->freeConnection($DBtag, $conn);
			
		return $isreturn;
	}
	
	public function insert($DBtag, $sql)
	{
		$returnID 	= 0;
		$conn 		= null;
		
		try{
			$conn 	= $this->getConnection($DBtag);
			$rs  	= mysql_query($sql, $conn);

			if($rs){
				$returnID = mysql_insert_id($conn);
			}
		}catch(Exception $e){
			echo mysql_error($conn) . $sql;
		}
		
		if($conn != null)
			$this->freeConnection($DBtag, $conn);
			
		return $returnID;
	}
	
	function insertUpdate($DBtag, $table, $data, $action = 'insert', $parameters = '') 
	{
	   	$isreturn 	= 0;
		$conn 		= null;
		
		try{
			$conn 	= $this->getConnection($DBtag);
			
		   	reset($data);
		    if ($action == 'insert') {
		      	$query = 'insert into ' . $table . ' (';
		      	while (list($columns, ) = each($data)) {
		        	$query .= $columns . ', ';
		      	}
		      	
		      	$query = substr($query, 0, -2) . ') values (';
		      	reset($data);
		      	while (list(, $value) = each($data)) {
		        	switch ((string)$value) {
		          		case 'now()':
		            		$query .= 'now(), ';
		            		break;
		            	case 'UTC_TIMESTAMP()':
		            		$query .= 'UTC_TIMESTAMP(), ';
		            		break;
		          		case 'null':
		            		$query .= 'null, ';
		            		break;
		          		default:
		            		$query .= "'" . $this->escape_string($value, $conn) . "', ";
		            		break;
		        	}
		      	}
		      	
		      	$query  = substr($query, 0, -2);
		      	
		      	$query .= ")";
		      	
		      	$query .= $parameters;;
		      	
		    } elseif ($action == 'update') {
		      	$query = 'update ' . $table . ' set ';
		      	
		      	while (list($columns, $value) = each($data)) {
		        	switch ((string)$value) {
		          		case 'now()':
		            		$query .= $columns . ' = now(), ';
		            		break;
		            	case 'UTC_TIMESTAMP()':
		            		$query .= 'UTC_TIMESTAMP(), ';
		            		break;
		          		case 'null':
		            		$query .= $columns .= ' = null, ';
		            		break;
		          		default:
		            		$query .= $columns . " = '" . $this->escape_string($value, $conn) . "', ";
		            		break;
		        	}
		      	}
		      	
		      	$query = substr($query, 0, -2) . ' where ' . $parameters;
		    }
		
			
		   	$rs  = mysql_query($query, $conn) or die("<br><br>Invalid query: " . $query . mysql_error($conn));

			if($rs){
				if ($action == 'insert') {
					$isreturn = mysql_insert_id($conn);
				}else{
					$isreturn = mysqli_affected_rows($conn);
				}
			}
		}catch(Exception $e){
			echo mysql_error($conn) . $query;
		}
		
		if($conn != null)
			$this->freeConnection($DBtag, $conn);
			
		return $isreturn;
  	}
  
	function escape_string($string, $conn) 
	{
//	    if (function_exists('mysql_real_escape_string')) {
//	      	return mysql_real_escape_string($string, $conn);
//	    } elseif (function_exists('mysql_escape_string')) {
//	      	return mysql_escape_string($string);
//	    }
	
	    return addslashes($string);
	}
	
	/* web list by condition
	 *
	 * @param  String DBtag # DB tag
	 * @param  String sql
	 * @return Array[][]
	 */
	public function getColumn($DBtag, $sql)
	{
		$isreturn 	= '';
		$conn 		= null;
		
		try{
			$conn 	= $this->getConnection($DBtag);
			$rs  	= mysql_query($sql, $conn);// or die("Invalid query: " . $sql . mysql_error($conn));

			if($arrCache = mysql_fetch_row($rs)){
				$isreturn = $arrCache[0];
			}
			
			mysql_free_result($rs);
		}catch(Exception $e){
			echo mysql_error($conn) . $sql;
		}
		
		if($conn != null)
			$this->freeConnection($DBtag, $conn);
			
		return $isreturn;
	}
	
	public function getColumns($DBtag, $sql)
	{
		$arrback 	= array();
		$conn 		= null;
		
		try{
			$conn 	= $this->getConnection($DBtag);
			$rs  	= mysql_query($sql, $conn);

			while($arrCache = mysql_fetch_row($rs)){
				$arrback[] = $arrCache[0];
			}
		}catch(Exception $e){
			echo mysql_error($conn) . $sql;
		}
		
		if($conn != null)
			$this->freeConnection($DBtag, $conn);
			
		return $arrback;
	}
	
	/* web by condition
	 *
	 * @param  string condition
	 * @return mixed  false: sql error  array: news info
	 */
	public function getAssoc($DBtag, $columns, $where, $orders = '', $page = 0, $discount = 20, $url = '')
	{
		$arrback 	= array();
		$conHandle 	= null;
		
		try{
			$conHandle 	= $this->getConnection($DBtag);
	
			$sql = 'SELECT count(*) FROM '.$where;
			$rs  = mysql_query($sql, $conHandle) or die (mysql_error($conHandle));
			
			list($total) = mysql_fetch_row($rs);
			$this->mutilPager($total, $page, $discount, $url);
			if(!empty($total)){
				if(empty($discount))
					$sql = "SELECT $columns FROM $where $orders";
				else{
					$sql = "SELECT $columns FROM $where $orders LIMIT $this->firstcount, $discount";
				}
				
				$rs  = mysql_query($sql, $conHandle) or die (mysql_error($conHandle));
				if($rs){
					while(is_array($arrtmp = mysql_fetch_assoc($rs))){
						$arrback[] = $arrtmp;
					}
				}
			}
		}catch(Exception $e){
			echo mysql_error($conHandle) . $sql;
		}
		
		if($conHandle != null)
			$this->freeConnection($DBtag, $conHandle);
			
		return $arrback;
	}
	
	/* web list by condition
	 *
	 * @param  String DBtag # DB tag
	 * @param  String sql
	 * @return Array[][]
	 */
	public function getHash($DBtag, $sql)
	{
		$arrBack 	= array();
		$conHandle 	= null;
		
		try{
			$conHandle = $this->getConnection($DBtag);

			$rs  = mysql_query($sql, $conHandle) or die($sql . mysql_error($conHandle));
			if($rs){
				while($arrCache = mysql_fetch_row($rs)){
					$arrBack[$arrCache[0]] = $arrCache[1];
				}
			}
		}catch(Exception $e){
			echo mysql_error($conHandle) . $sql;
		}
		
		if($conHandle != null)
			$this->freeConnection($DBtag, $conHandle);
			
		return $arrBack;
	}
	

	/* custom condition
	 *
	 * @param  string condition
	 * @return mixed  false: sql error  array: news info
	 */
	public function listCustom($DBTag, $columns, $where, $orders, $page = 0, $discount = 20, $url = '')
	{
		$arrback = array();
		
		try{
			$conn = $this->getConnection($DBTag);
	
			$sql = 'SELECT count(*) FROM '.$where;
	
			$rs  = mysql_query($sql, $conn) or die ($sql . mysql_error($conn));
			list($total) = mysql_fetch_row($rs) or die ($sql . mysql_error($conn));
			$this->mutilPager($total, $page, $discount, $url);
			
			if(!empty($total)){
				if(empty($discount))
					$sql = "SELECT $columns FROM $where";
				else{
					$sql = "SELECT $columns FROM $where $orders LIMIT $this->firstcount, $discount";
				}
				
				$rs  = mysql_query($sql, $conn) or die ($sql . mysql_error($conn));
				if($rs){
					while(is_array($arrtmp = mysql_fetch_array($rs))){
						$arrback[] = $arrtmp;
					}
				}
			}
		}catch(Exception $e){
			echo mysql_error($conn) . $sql;
		}
		
		if($conn != null)
			$this->freeConnection($DBTag, $conn);
			
		return $arrback;
	}
	

}

?>
